package com.tongguan.paypos.activity.trans;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.tongguan.paypos.R;
import com.tongguan.paypos.adapter.PayTypeAdapter;
import com.tongguan.paypos.base.BaseActivity;
import com.tongguan.paypos.base.MyApplication;
import com.tongguan.paypos.common.AppConstants;
import com.tongguan.paypos.common.RequestCallback;
import com.tongguan.paypos.common.UrlConstants;
import com.tongguan.paypos.common.User;
import com.tongguan.paypos.entity.CouponInfo;
import com.tongguan.paypos.entity.PayInfo;
import com.tongguan.paypos.entity.PayType;
import com.tongguan.paypos.entity.PayTypeInfo;
import com.tongguan.paypos.entity.TransInfo;
import com.tongguan.paypos.entity.TransUnionInfo;
import com.tongguan.paypos.fragment.ResultOrderDetailFragment;
import com.tongguan.paypos.interfaces.impl.CashContext;
import com.tongguan.paypos.interfaces.impl.CashRebate;
import com.tongguan.paypos.interfaces.impl.CashReduce;
import com.tongguan.paypos.utils.AppUtils;
import com.tongguan.paypos.utils.Arith;
import com.tongguan.paypos.utils.CipherUtils;
import com.tongguan.paypos.utils.L;
import com.tongguan.paypos.utils.NumberUtils;
import com.tongguan.paypos.utils.SPUtils;
import com.tongguan.paypos.utils.ToastUtils;
import com.tongguan.paypos.utils.Utils;
import com.tongguan.paypos.view.CustomAlertDialog;
import com.uuzuche.lib_zxing.activity.CaptureActivity;
import com.uuzuche.lib_zxing.activity.CodeUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import okhttp3.Call;

public class PayTypeSelectActivity extends BaseActivity {

    public final static String MONEY = "money";
    public final static String ORDER_ID = "orderId";

    private static final int REQUEST_CODE_WX = 10001;
    private static final int REQUEST_CODE_ZFB = 10002;
    private static final int REQUEST_CODE_YZF = 10003;
    private static final int REQUEST_CODE_HYC = 10004;
    private static final int REQUEST_CODE_QQ = 10005;
    private static final int REQUEST_CODE_POS = 10006;
    private static final int REQUEST_CODE_POS_DK = 10007;
    //    private static final int REQUEST_CODE_POS_WK = 10008;
    private static final int REQUEST_CODE_COUPON = 10009;
    private static final int REQUEST_CODE_YLSM = 10010;
    private static final int DELAYED_TIME = 5000;//
    private static final String UNIT = "元";//单位

    @BindView(R.id.gv_pay_type)
    GridView mGvPayType;
    @BindView(R.id.order_number)
    TextView mOrderNumber;
    @BindView(R.id.tv_money)
    TextView mTvMoney;
    @BindView(R.id.v_coupon)
    View mVCoupon;
    @BindView(R.id.tv_coupon_money)
    TextView mTvCouponMoney;
    @BindView(R.id.ll_coupon)
    LinearLayout mLlCoupon;
    @BindView(R.id.btn_add_coupon)
    Button mBtnAddCoupon;
    @BindView(R.id.btn_query_integral)
    Button mBtnQueryIntegral;
    @BindView(R.id.ll_add_coupon)
    LinearLayout mLlAddCoupon;
    @BindView(R.id.tv_coupon_name)
    TextView mTvCouponName;
    @BindView(R.id.tv_coupon_number)
    TextView mTvCouponNumber;
    @BindView(R.id.ll_coupon_info)
    LinearLayout mLlCouponInfo;
    @BindView(R.id.tv_amount)
    TextView mTvAmount;

    private PayTypeAdapter mAdapter;
    private ArrayList<PayType> mPayTypes = new ArrayList<>();
    private double money;//实付金额
    private long coupon_money = 0L;//优惠金额 （单位分）
    //  private String coupon_info;//优惠二维码信息
    private double amount;//总计
    private String coupon_name;//券名
    private String coupon_number = "";//券号
    private String orderId;

    private int count = 3;//查询次数
    private int count_sync = 3;//同步查询次数

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_pay_type_select);
        ButterKnife.bind(this);
        initTile(R.string.title_pey_select, true);
        Bundle bundle = getIntent().getExtras();
        if (bundle != null) {
            money = bundle.getDouble(MONEY);
            orderId = bundle.getString(ORDER_ID);
            amount = money;
        }
        initView();
        initPayType();
        initEvent();
    }


    private void initView() {
        mOrderNumber.setText(orderId);
        String temp = NumberUtils.getMoneyTypeIgnore(money) + UNIT;
        mTvMoney.setText(temp);
        resetAmount();
        mAdapter = new PayTypeAdapter(context, mPayTypes);
        mGvPayType.setAdapter(mAdapter);
    }

    /**
     * 加载支付方式
     */
    private void initPayType() {
        if (MyApplication.getInstance().getPayTypes() == null) {
            params = new HashMap<>();
            params.put(UrlConstants.KEY_ACCOUNT, User.getInstance().getAccount());
            RequestCallback.post(context, UrlConstants.GET_PAY_TYPE, params, new AbstractRequestCallback() {
                @Override
                public void onResponse(String response, int id) {
                    PayTypeInfo payTypeInfo = PayTypeInfo.objectFromData(response);
                    if (payTypeInfo.getStatus() != 100) {
                        ToastUtils.showCustom(context, payTypeInfo.getMessage());
                        return;
                    }
                    List<PayTypeInfo.PayTypesBean> payTypes = payTypeInfo.getPayTypes();
                    if (payTypes == null || payTypes.size() == 0) {
                        ToastUtils.showCustom(context, "无支付方式");
                        return;
                    }
                    //固定支付方式
                    for (PayTypeInfo.PayTypesBean payType : payTypes) {
                        PayType data = AppConstants.payTypeMap.get(payType.getType());
                        if (data == null){
                            continue;
                        }
                        if ("JF".equals(data.getType())) { //积分支付
                            mBtnQueryIntegral.setVisibility(View.VISIBLE);
                        }
                        mPayTypes.add(data);
                    }
                    if (mPayTypes.size() == 0) {
                        L.d("支付方式不在本地中");
                        return;
                    }
                    if (MyApplication.getInstance().getPayTypes() == null) {
                        MyApplication.getInstance().setPayTypes(mPayTypes);
                    }
                    mAdapter.notifyDataSetChanged();
                }
            });
        } else {
            ArrayList<PayType> payTypes = MyApplication.getInstance().getPayTypes();
            if (payTypes.size() == 0) {
                L.d("支付方式不在本地中");
                return;
            }
            for (PayType payType : payTypes) {
                if (payType == null){
                    continue;
                }
                if ("JF".equals(payType.getType())) { //积分支付
                    mBtnQueryIntegral.setVisibility(View.VISIBLE);
                }
                mPayTypes.add(payType);
            }
            mAdapter.notifyDataSetChanged();
        }
    }

    private void initEvent() {
        mGvPayType.setOnItemClickListener((parent, view, position, id) -> {
            switch (mAdapter.getItem(position).getId()) {
                case 0: //微信
                    scanQRCode(REQUEST_CODE_WX, "微信扫一扫");
                    break;
                case 1://支付宝
                    scanQRCode(REQUEST_CODE_ZFB, "支付宝扫一扫");
                    break;
                case 2://翼支付
                    scanQRCode(REQUEST_CODE_YZF, "翼支付扫一扫");
                    break;
                case 3://现金支付
                    new CustomAlertDialog.Builder(context).setTitle(R.string.common_tip_title).setMessage("确定现金支付？")
                            .setPositiveButton(R.string.common_sure, (dialog, which) -> cashPay())
                            .setNegativeButton(R.string.common_cancel, null).show();
                    break;
                case 4://会员卡
                    if (coupon_money > 0) {
                        ToastUtils.showCustom(context, "会员卡不能使用优惠券");
                        return;
                    }
                    scanQRCode(REQUEST_CODE_HYC, "会员卡扫一扫");
                    break;
                case 5://qq
                    scanQRCode(REQUEST_CODE_QQ, "QQ钱包扫一扫");
                    break;
                case 6: //刷卡支付
                    if (coupon_money > 0) {
                        ToastUtils.showCustom(context, "不能使用优惠券");
                        return;
                    }
                    Bundle bundle = new Bundle();
                    bundle.putString("amount",NumberUtils.getDoubleFormat(amount));
                    AppUtils.runComponent(PayTypeSelectActivity.this, AppConstants.UNION_PAY_APP_PACKAGE, AppConstants.SALE_DIR, bundle, REQUEST_CODE_POS);
                    break;
                case 7: //积分
                    if (coupon_money > 0) {
                        ToastUtils.showCustom(context, "不能使用优惠券");
                        return;
                    }
                    ToastUtils.showCustom(context, "此版本暂不开放！");
                    break;
                case 8://代扣
                    if (coupon_money > 0) {
                        ToastUtils.showCustom(context, "不能使用优惠券");
                        return;
                    }
                    ToastUtils.showCustom(context, "此版本暂不支持！");
                    break;
                case 9://外卡
                    //签到
                    //activity跳转
                    if (coupon_money > 0) {
                        ToastUtils.showCustom(context, "不能使用优惠券");
                        return;
                    }
                    ToastUtils.showCustom(context, "此版本暂不支持！");
                    break;
                case 10://银联钱包
                    scanQRCode(REQUEST_CODE_YLSM,"银联钱包扫码");
                    break;
            }
        });

        mBtnQueryIntegral.setOnClickListener(v -> ToastUtils.showCustom(context, "暂不开放！"));
        mBtnAddCoupon.setOnClickListener(v -> {
            if (money < 1) {
                ToastUtils.showCustom(context, "金额限制，最低1元");
                return;
            }
            new CustomAlertDialog.Builder(context).setTitle(R.string.common_tip_title).setMessage("扫描电子版或纸质二维码？")
                    .setPositiveButton(R.string.common_sure, (dialog, which) ->
                            startActivityForResult(new Intent(this, CaptureActivity.class), REQUEST_CODE_COUPON))
                    .setNegativeButton(R.string.common_cancel, null).show();
        });
    }

    private void scanQRCode(int requestCode, String title) {
        Intent intent = new Intent(context, CaptureActivity.class);
        Bundle bundle = new Bundle();
        bundle.putString("title", title);
        bundle.putString("money", NumberUtils.getMoneyTypeIgnore(amount));
        intent.putExtras(bundle);
        startActivityForResult(intent, requestCode);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        L.d("requestCode = " + requestCode + " resultCode = " + resultCode);
        if (data != null) {
            Bundle bundle = data.getExtras();
            if (bundle == null) {
                return;
            }
            //线上支付
            if (requestCode == REQUEST_CODE_WX || requestCode == REQUEST_CODE_ZFB || requestCode == REQUEST_CODE_YZF ||
                    requestCode == REQUEST_CODE_QQ || requestCode == REQUEST_CODE_YLSM) {
                if (bundle.getInt(CodeUtils.RESULT_TYPE) == CodeUtils.RESULT_SUCCESS) {
                    String result = bundle.getString(CodeUtils.RESULT_STRING);
                    onlinePay(result, requestCode);
                } else if (bundle.getInt(CodeUtils.RESULT_TYPE) == CodeUtils.RESULT_FAILED) {
                    L.d("解析二维码失败");
                }
            }
            //会员卡
            if (requestCode == REQUEST_CODE_HYC) {
                if (bundle.getInt(CodeUtils.RESULT_TYPE) == CodeUtils.RESULT_SUCCESS) {
                    String result = bundle.getString(CodeUtils.RESULT_STRING);
                    memberPay(result);
                } else if (bundle.getInt(CodeUtils.RESULT_TYPE) == CodeUtils.RESULT_FAILED) {
                    L.d("解析二维码失败");
                }
            }
            //优惠券
            if (requestCode == REQUEST_CODE_COUPON) {
                if (bundle.getInt(CodeUtils.RESULT_TYPE) == CodeUtils.RESULT_SUCCESS) {
                    String result = bundle.getString(CodeUtils.RESULT_STRING);
                    couponInfoPay(result);
                } else if (bundle.getInt(CodeUtils.RESULT_TYPE) == CodeUtils.RESULT_FAILED) {
                    L.d("解析二维码失败");
                }
            }
        }
        //银联
        if (requestCode == REQUEST_CODE_POS) {
            if (resultCode == RESULT_OK) {
                String result = data.getStringExtra("result");
                String message = Utils.assembleTransUnionInfo(result, true);
                L.d(message);
                finish();
            } else {
                ToastUtils.showCustom(context, "支付取消或失败");
            }
        }
    }

    /**
     * 获取优惠券信息
     */
    private void couponInfoPay(String result) {
        coupon_number = result;
        params = new HashMap<>();
        params.put(UrlConstants.KEY_ACCOUNT, User.getInstance().getAccount());
        params.put(UrlConstants.KEY_COUPON, result);
        RequestCallback.post(context, UrlConstants.GET_DISCOUNT_COUPON, params, mDialog, new AbstractRequestCallback() {
            @Override
            public void onResponse(String response, int id) {
                CouponInfo couponInfo = CouponInfo.objectFromData(response);
                if (couponInfo.getStatus() != 100) {
                    ToastUtils.showCustom(context, couponInfo.getMessage());
                    return;
                }
                coupon_name = couponInfo.getTitle();
                CashContext cc;  //单位是分
                if ("CASH".equals(couponInfo.getCoupon_type())) {
                    //满减  满优惠金额 减 多少 最小大于0.01
                    coupon_money = Long.parseLong(couponInfo.getReduce());
                    double parseDouble = Arith.div(Double.parseDouble(couponInfo.getReduce()), 100);
                    if (parseDouble >= money) {
                        new CustomAlertDialog.Builder(context).setTitle(R.string.common_tip_title).setMessage("支付金额必须大于优惠金额")
                                .setPositiveButton(R.string.common_sure, null).show();
                        return;
                    }
                    cc = new CashContext(new CashReduce(parseDouble, parseDouble));
                    amount = cc.getResult(money); // 总计
                    resetView(parseDouble);
                } else if ("DISCOUNT".equals(couponInfo.getCoupon_type())) {
                    //折扣 1-100
                    double rebate = Arith.div(Integer.parseInt(couponInfo.getDiscount()), 100);
                    cc = new CashContext(new CashRebate(rebate));
                    amount = cc.getResult(money);// 总计
                    double sub = Arith.sub(money, amount);
                    coupon_money = (long) Arith.mul(sub, 100);
                    resetView(sub);
                }
            }
        });
    }

    /**
     * 线上统一支付 （异常需要发查询）
     *
     * @param result      扫码返回
     * @param requestCode 类型
     */
    private void onlinePay(String result, int requestCode) {
        String pay_type = "";
        switch (requestCode) {
            case REQUEST_CODE_WX:
                pay_type = "WX";
                break;
            case REQUEST_CODE_ZFB:
                pay_type = "ZFB";
                break;
            case REQUEST_CODE_YZF:
                pay_type = "YZF";
                break;
            case REQUEST_CODE_QQ:
                pay_type = "QQ";
                break;
            case REQUEST_CODE_YLSM:
                pay_type = "YLSM";
                break;
        }
        params = new HashMap<>();
        params.put(UrlConstants.KEY_ACCOUNT, User.getInstance().getAccount());
        params.put(UrlConstants.KEY_POS_ID, User.getInstance().getPosId());
        params.put(UrlConstants.KEY_ORDER_ID, orderId);
        params.put(UrlConstants.KEY_COUPON_MONEY, coupon_money);
        params.put(UrlConstants.KEY_COUPON_INFO, coupon_number);
        params.put(UrlConstants.KEY_PAY_MONEY, String.valueOf(money));
        params.put(UrlConstants.KEY_BARCODE, result);
        params.put(UrlConstants.KEY_CHANNEL_ID, pay_type);
//        params.put(UrlConstants.KEY_NONCE_STR, Utils.getRand32());
//        params.put(UrlConstants.KEY_SIGN,signKey(params));
        RequestCallback.post(context, UrlConstants.UNIFY_PAY, params, mDialog, new RequestCallback.HttpCallback() {
            @Override
            public void onResponse(String response, int id) {
                PayInfo payInfo = PayInfo.objectFromData(response);
                String message = payInfo.getMessage();
                if (payInfo.getStatus() != 100) {
                    if (AppConstants.messageFilter(message)) { //用户问题拦截
                        new CustomAlertDialog.Builder(context).setTitle(R.string.common_tip_title)
                                .setMessage(message)
                                .setPositiveButton(R.string.common_sure, (dialog, which) -> finish())
                                .show();
                        return;
                    }
                    ToastUtils.showCustom(context, message);
                    //查询上游 订单
                    queryOder(message);
                    return;
                }
                if (!"0".equals(payInfo.getState())) {
                    //查询上游 订单
                    queryOder(message);
                    return;
                }
//                queryOderDetail(); //暂时再次查询
                TransInfo transInfo = payInfo.getTransInfo();
                if (transInfo == null) {
                    //查询详情
                    queryOderDetail();
                    return;
                }
                //成功跳转
                successJumpAct(transInfo, payInfo.getWxImgUrl());
            }

            @Override
            public void onError(Call call, Exception e, int id) {
                queryOder("支付网络异常");
            }
        });
    }

    /**
     * 会员支付 （系统内不需要查询）
     */
    private void memberPay(String result) {
        params = new HashMap<>();
        params.put(UrlConstants.KEY_ACCOUNT, User.getInstance().getAccount());
        params.put(UrlConstants.KEY_POS_ID, User.getInstance().getPosId());
        params.put(UrlConstants.KEY_ORDER_ID, orderId);
        params.put(UrlConstants.KEY_COUPON_MONEY, coupon_money);
        params.put(UrlConstants.KEY_COUPON_INFO, coupon_number);
        params.put(UrlConstants.KEY_PAY_MONEY, String.valueOf(money));
        params.put(UrlConstants.KEY_CARD_NO, result);
//        params.put(UrlConstants.KEY_NONCE_STR, Utils.getRand32());
//        params.put(UrlConstants.KEY_SIGN,signKey(params));
        RequestCallback.post(context, UrlConstants.MEMBER_PAY, params, mDialog, new AbstractRequestCallback() {
            @Override
            public void onResponse(String response, int id) {
                //{"message":"支付成功","status":100,"state":"0"}
                PayInfo payInfo = PayInfo.objectFromData(response);
                if (payInfo.getStatus() != 100) {
                    String message = payInfo.getMessage();
                    if (AppConstants.messageFilter(message)) { //用户问题拦截
                        new CustomAlertDialog.Builder(context).setTitle(R.string.common_tip_title)
                                .setMessage(message)
                                .setPositiveButton(R.string.common_sure, (dialog, which) -> finish())
                                .show();
                        return;
                    }
                    ToastUtils.showCustom(context, payInfo.getMessage());
                    return;
                }
                if (!"0".equals(payInfo.getState())) {
                    ToastUtils.showCustom(context, payInfo.getMessage());
                    return;
                }
                TransInfo transInfo = payInfo.getTransInfo();
                if (transInfo == null) {
                    //查询详情
                    queryOderDetail();
                    return;
                }
                successJumpAct(transInfo, payInfo.getWxImgUrl());
            }
        });
    }

    /**
     * 现金
     */
    private void cashPay() {
        params = new HashMap<>();
        params.put(UrlConstants.KEY_ACCOUNT, User.getInstance().getAccount());
        params.put(UrlConstants.KEY_POS_ID, User.getInstance().getPosId());
        params.put(UrlConstants.KEY_ORDER_ID, orderId);
        params.put(UrlConstants.KEY_COUPON_MONEY, coupon_money);
        params.put(UrlConstants.KEY_COUPON_INFO, coupon_number);
        params.put(UrlConstants.KEY_PAY_MONEY, String.valueOf(money));
        RequestCallback.post(context, UrlConstants.CASH_PAY, params, mDialog, new AbstractRequestCallback() {
            @Override
            public void onResponse(String response, int id) {
                PayInfo payInfo = PayInfo.objectFromData(response);
                if (payInfo.getStatus() != 100) {
                    ToastUtils.showCustom(context, payInfo.getMessage());
                    return;
                }
                if (!"0".equals(payInfo.getState())) {
                    return;
                }
                TransInfo transInfo = payInfo.getTransInfo();
                if (transInfo == null) {
                    //查询详情
                    queryOderDetail();
                    return;
                }
                successJumpAct(transInfo, payInfo.getWxImgUrl());
            }
        });
    }

    /**
     * 查询上游订单接口
     *
     * @param msg 状态
     */
    private void queryOder(String msg) {
        if (mDialog != null && !mDialog.isShowing()) {
            mDialog.show();
            mDialog.setLoadingMessage(msg + "\n正在查询，请稍等...");
        }
        params = new HashMap<>();
        params.put(UrlConstants.KEY_ACCOUNT, User.getInstance().getAccount());
        params.put(UrlConstants.KEY_POS_ID, User.getInstance().getPosId());
        params.put(UrlConstants.KEY_ORDER_ID, orderId);
//        params.put(UrlConstants.KEY_NONCE_STR, Utils.getRand32());
//        params.put(UrlConstants.KEY_SIGN,signKey(params));
        RequestCallback.post(context, UrlConstants.QUERY_ORDER, params, new RequestCallback.HttpCallback() {
            @Override
            public void onResponse(String response, int id) {
                PayInfo payInfo = PayInfo.objectFromData(response);
                String message = payInfo.getMessage();
                if (payInfo.getStatus() != 100) {
                    //查询状态还是失败 继续查询
                    if (AppConstants.messageFilter(message)) { // 问题拦截
                        new CustomAlertDialog.Builder(context).setTitle(R.string.common_tip_title)
                                .setMessage(message)
                                .setPositiveButton(R.string.common_sure, (dialog, which) -> finish())
                                .show();
                        return;
                    }
                    mHandler.sendMessageDelayed(mHandler.obtainMessage(0, message), DELAYED_TIME);
                    return;
                }
                if (!"0".equals(payInfo.getState())) {
                    //查询上游 订单
                    mHandler.sendMessageDelayed(mHandler.obtainMessage(0, message), DELAYED_TIME);
                    return;
                }
                TransInfo transInfo = payInfo.getTransInfo();
                if (transInfo == null) {
                    //查询详情
                    queryOderDetail();
                    return;
                }
                if (mDialog != null && mDialog.isShowing()) {
                    mDialog.dismiss();
                }
                //成功跳转
                successJumpAct(transInfo, payInfo.getWxImgUrl());
            }

            @Override
            public void onError(Call call, Exception e, int id) {
                mHandler.sendMessageDelayed(mHandler.obtainMessage(0, "查询订单网络异常"), DELAYED_TIME);
            }
        });
    }

    /**
     * 查询订单详情接口
     */
    private void queryOderDetail() {
        params = new HashMap<>();
        params.put(UrlConstants.KEY_ACCOUNT, User.getInstance().getAccount());
        params.put(UrlConstants.KEY_POS_ID, User.getInstance().getPosId());
        params.put(UrlConstants.KEY_ORDER_ID, orderId);
        RequestCallback.post(context, UrlConstants.ORDER_DETAILS + orderId, params, new AbstractRequestCallback() {
            @Override
            public void onResponse(String response, int id) {

                PayInfo payInfo = PayInfo.objectFromData(response);
                if (payInfo.getStatus() != 100) {
                    ToastUtils.showCustom(context, payInfo.getMessage());
                    return;
                }
                TransInfo transInfo = payInfo.getTransInfo();
                if (transInfo == null) {
                    new CustomAlertDialog.Builder(context).setTitle(R.string.common_tip_title)
                            .setMessage(payInfo.getMessage() + "\n订单详情查询失败，是否重新请求")
                            .setPositiveButton(R.string.common_sure, (dialog, which) -> queryOderDetail())
                            .setNegativeButton(R.string.common_cancel, null).show();
                    return;
                }
                if (!"0".equals(transInfo.getState())) {
                    //防止数据查询接口和订单详情接口没同步
                    if (mDialog != null && !mDialog.isShowing()) {
                        mDialog.show();
                        mDialog.setLoadingMessage("详情状态错误，重新查询...");
                    }
                    mHandler.sendMessageDelayed(mHandler.obtainMessage(1, ""), DELAYED_TIME);
                }
                //成功跳转
                successJumpAct(transInfo, payInfo.getWxImgUrl());
            }

            @Override
            public void onError(Call call, Exception e, int id) {
                super.onError(call, e, id);
                new CustomAlertDialog.Builder(context).setTitle(R.string.error_net)
                        .setMessage(e.getMessage())
                        .setPositiveButton("重新加载", (dialog, which) -> queryOderDetail())
                        .setNegativeButton(R.string.common_cancel, null).show();
            }
        });
    }

    /**
     * 带优惠券时的二维码连接
     */
    private void successJumpAct(TransInfo info, String wxImageUrl) {
        Bundle bundle = new Bundle();
        bundle.putParcelable(ResultOrderDetailFragment.ORDER_DATA, info);
        bundle.putString(ResultOrderDetailFragment.WX_IMG_URL, wxImageUrl);
        bundle.putString(ResultManageActivity.EXCHANGE_FRAGMENT_NAME, ResultOrderDetailFragment.class.getName());
        jumpAct(ResultManageActivity.class, bundle, false, true);
    }

    //延时
    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (!isFinishing()) {
                switch (msg.what) {
                    case 0:
                        if (mDialog != null) {
                            mDialog.dismiss();
                        }
                        String message = (String) msg.obj;
                        if (count > 0) {
                            queryOder(message);
                            count--;
                        } else {
                            new CustomAlertDialog.Builder(context).setTitle("支付异常")
                                    .setMessage(message)
                                    .setPositiveButton("再次查询", (dialog, which) -> queryOder(message))
                                    .setNegativeButton("取消订单", (dialog, which) -> finish()).show();
                        }
                        break;
                    case 1:
                        if (mDialog != null) {
                            mDialog.dismiss();
                        }
                        if (count_sync > 0) {
                            queryOderDetail();
                            count_sync--;
                        } else {

                            new CustomAlertDialog.Builder(context).setTitle("支付异常")
                                    .setMessage("订单数据支付状态不成功")
                                    .setPositiveButton("再次查询", (dialog, which) -> queryOderDetail())
                                    .setNegativeButton("取消订单", (dialog, which) -> finish()).show();
                        }
                        break;
                }
            }
        }
    };

    //重设金额
    private void resetAmount() {
        String temp = NumberUtils.getMoneyTypeIgnore(amount) + UNIT;
        mTvAmount.setText(temp);
    }

    //重设视图
    private void resetView(double couponMoney) {
        mBtnAddCoupon.setVisibility(View.GONE);//隐藏按钮
        mLlCoupon.setVisibility(View.VISIBLE);//显示信息
        mVCoupon.setVisibility(View.VISIBLE);
        mLlCouponInfo.setVisibility(View.VISIBLE);
        mTvCouponMoney.setText("-" + NumberUtils.getMoneyTypeIgnore(couponMoney) + UNIT); //设置优惠金额
        mTvCouponName.setText(coupon_name);
        mTvCouponNumber.setText(coupon_number);
        resetAmount();
    }

    //签名
    private String signKey(Map map) {
        String key = (String) SPUtils.getSp(context, AppConstants.SIGNATURE, "");
        return CipherUtils.Signature(map, key);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        RequestCallback.cancelAllRequest();
        mHandler.removeMessages(0);
    }
}
